# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 12:57:27 2018

@author: nxleisp
"""


#curl -u admin@zaadmin01:zaadmin01 -i http://10.70.49.31/tsdbrest/api/token

#curl -u admin@zaadmin01:zaadmin01 -i http://10.70.49.31/tsdbrest/api/instance


#http://10.70.49.31/tsdbrest/api/instance/range/1234/7?limit=10&start_time=1442559920000&end_time=1442559970000&cursor_mask=*&token=bea1e09da4a34d07bd638f052fce73b5


import pandas
import requests
from requests.auth import HTTPBasicAuth
import json,time

class xtsdb():
    _host = ''
    _port = ''
    _user = ''
    _pswd = ''
    _url_token = ''
    _url_instance = ''
    _url_record = ''
    _url_tag = ''
    _token = ''
        
    def __init__(self,host='10.70.248.146',port=80,user='admin@BGTATOADMN01',pswd='admin'):
        self._host = host
        self._port = port
        self._user = user
        self._pswd = pswd
        self._url_base = 'http://%s:%s' % (host,port)
        self._url_token = self._url_base + '/tsdbrest/api/token'	
        self._url_instance = self._url_base + '/tsdbrest/api/instance'	
        self._url_record = self._url_base + '/tsdbrest/api/record'	
        self._url_tag = self._url_base + '/tsdbrest/api/tag'
        #self._url_tagquery = self._url_base + '/tsdbrest/api/tag/querybytagname'
        self.getToken()
    
    
    
    def getToken(self):
        r = requests.get(self._url_token,auth=(self._user,self._pswd))
        self._token = r.json()['token']
        return r.json()
        
    def getInstance(self,instance_name,property_names=None):
        headers = {'Content-Type': 'application/json'}
        if(property_names==None):
            r = requests.post(self._url_instance,data=json.dumps([{"instance_name":instance_name}]),headers=headers,auth=(self._user,self._pswd))            
        else:
            r = requests.post(self._url_instance,data=json.dumps([{"instance_name":instance_name,"property_names":property_names}]),headers=headers,auth=(self._user,self._pswd))            
        return r.json()
        
    def putRecord(self,instance_id,property_values=None):
        headers = {'Content-Type': 'application/json'}
        r = requests.post(self._url_record,data=json.dumps([{"instance_id":instance_id,"property_values":property_values}]),headers=headers,auth=(self._user,self._pswd))            
        return r.json()
    
    
    def getSnapshot(self,instance_id,property_ids=None):
        headers = {'Content-Type': 'application/json'}
        r = requests.post(self._url_record+'/snapshot',data=json.dumps([{"instance_id":instance_id,"property_ids":property_ids}]),headers=headers,auth=(self._user,self._pswd))            
        return r.json()


    def getHistoryByID(self,instance_id,property_id,limit=10,start_time=None,end_time=None,cursor_mask='*'):
        if(end_time == None):
            end_time = str(time.time()).replace('.','')[:-4]
        if(start_time == None):
            start_time = str(int(end_time) - 300000)
        headers = {'Content-Type': 'application/json'}
        request_url =self._url_record+'/range/%s/%s?limit=%s&start_time=%s&end_time=%s&cursor_mask=%s' % (instance_id,property_id,limit,start_time,end_time,cursor_mask)
        print(request_url)
        r = requests.get(request_url,headers=headers,auth=(self._user,self._pswd))            
        print(r.content)
        return r.json()


    def getHistoryByTagID(self,tag_id,limit=10,start_time=None,end_time=None,cursor_mask='*'):
        if(end_time == None):
            end_time = str(time.time()).replace('.','')[:-4]
        if(start_time == None):
            start_time = str(int(end_time) - 300000)
        headers = {'Content-Type': 'application/json'}
        request_url =self._url_record+'/tag/range/%s?limit=%s&start_time=%s&end_time=%s&cursor_mask=%s' % (tag_id,limit,start_time,end_time,cursor_mask)
        print(request_url)
        r = requests.get(request_url,headers=headers,auth=(self._user,self._pswd))            
        print(r.content)
        return r.json()




    def timeconvert(self,stime):
        time_stamp = time.strptime("%Y%m%d%H%M%S", stime)
        

    def get_time_stamp(self,ct):
        local_time = time.localtime(ct)
        data_head = time.strftime("%Y%m%d_%H%M%S", local_time)
        data_secs = (ct - int(ct)) * 1000
        time_stamp = "%s.%03d" % (data_head, data_secs)
        return time_stamp

    def getHistoryByName(self,instance_name,property_names,limit=10,start_time=None,end_time=None,upper_inclusive='true'):
        if(end_time == None):
            end_time = self.get_time_stamp(time.time())
        if(start_time == None):
            start_time = self.get_time_stamp(time.time()-300)
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_record+'/range/%s?limit=%s&start_time=%s&end_time=%s&upper_inclusive=%s' % (instance_name,limit,start_time,end_time,upper_inclusive)
        print(request_url)
        r = requests.post(request_url,data=json.dumps(property_names),headers=headers,auth=(self._user,self._pswd))            
        return r.json()


    def getTagIdByName(self,tagnames,collector_name=None):
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_tag + '/querybytagname'
        print(request_url)
        r = requests.post(request_url,data=json.dumps(tagnames),headers=headers,auth=(self._user,self._pswd))
        rst = None
        if(collector_name == None):
            rst = r.json()['records']
        else:
            for x in r.json()['records']:
                if(x['collector_name'] == collector_name):
                    rst = [x]
        return rst

    
    def getTagIdByNames(self,tagnames,collector_name=None):
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_tag + '/querybytagname'
        print(request_url)
        r = requests.post(request_url,data=json.dumps(tagnames),headers=headers,auth=(self._user,self._pswd))
        return r.json()['records']


    def getTagNameByCollector(self,collector_names=None):
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_tag + '/querybycollectorname?limit=1000&offset=0'
        print(request_url)
        r = requests.post(request_url,data=json.dumps(collector_names),headers=headers,auth=(self._user,self._pswd))
        return r.json()


    def getHistoryByTagNames(self,collector_name,tag_names,limit=1000,start_time=None,end_time=None,cursor_mask='*',minutes=5):
        tag_ids = []
        rst = {}
        if(end_time == None):
            end_time = str(time.time()).replace('.','')[:-4]
        if(start_time == None):
            start_time = str(int(end_time) - minutes*60*1000)
        headers = {'Content-Type': 'application/json'}
        for tag_name in tag_names:
            tag_idrst = self.getTagIdByName([tag_name],collector_name)
            if(tag_idrst != None):
                tag_id = tag_idrst[0]['tag_id']
                tag_ids.append(tag_id)
                request_url =self._url_record+'/tag/range/%s?limit=%s&start_time=%s&end_time=%s&cursor_mask=%s' % (tag_id,limit,start_time,end_time,cursor_mask)
                print(request_url)
                r = requests.get(request_url,headers=headers,auth=(self._user,self._pswd))   
                rst[tag_name] = r.json()
            #print(r.content)
        return rst


    def getSnapshotByTagIDs(self,tag_ids):
        headers = {'Content-Type': 'application/json'}
        request_url = self._url_record + '/tag/snapshot'
        print(request_url)
        r = requests.post(request_url,data=json.dumps(tag_ids),headers=headers,auth=(self._user,self._pswd))
        return r.json()
        

#def test():
#    #xdb = xtsdb()
#    xdb = xtsdb(host='10.70.50.121')
#    tk = xdb.getToken()
#    print(tk)
#    print('test for getInstance')
#    r = xdb.getInstance('test')
#    print(r)
#    print('test for getSnapshot')
#    r = xdb.getSnapshot('11423',[])
#    print(r)
#    r = xdb.getHistoryByTagNames('tongweisu1580',["Status.XRay1HighVoltage","Status.XRay1TubeCurrent"],minutes=1000)
##    print(r["Status.XRay1HighVoltage"]["records"])
#    import pandas as pd
#    
#    data = pd.DataFrame(r["Status.XRay1HighVoltage"]["records"])
#    print(data)
##    print(r)
#    print(r.items())
#    print(r.keys())
#    xdb.timeconvert("1543506589954")
#    print('test for getHistoryByID')
#    r = xdb.getHistoryByID('11423',6)
#    print(r)
#    print('test for getTagIdByName')
#    r = xdb.getTagIdByName(["Setup.CrownUpper"],'tongweisu1580')
#    print(r)
#    print('test for getHistoryByTagID')
#    r = xdb.getHistoryByTagID(r[0]['tag_id'])
#    print(r)
#    print('test for getHistoryByTagName')
#    r = xdb.getHistoryByTagNames('tongweisu1580',["Setup.CrownUpper","Setup.CrownLower"])
#    print(r)
#    r = xdb.getHistoryByTagNames('tongweisu1580',["ScanData.CoilID"])
#    print(r)
#    print('test for getTagNameByCollector')
#    r = xdb.getTagNameByCollector(['tongweisu1580'])
#    print(r)
    #print('test for getHistoryByName')
    #r = xdb.getHistoryByName('test',["FLOAT32"])
    #r = xdb.getTags(collector_name='ihd',tag_name='',limit=100,offset=0)


#test()

